package longAddrDemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class LongAdderTest {
    /**
     * AtomicLong存在性能瓶颈，由于使用CAS方法，高并发的情况下会造成大量的线程自锁，而只有一个线程
     * 会更新成功，浪费CPU资源
     * Lonadder的思想是将单一的原子变量拆分为多个变量，从而降低高并发下的资源争抢
     *
     */
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(100);
        // 类似还有 DoubleAdder DoubleAccumulator LongAccrmulator 以及继承子LongAddr 的 LongAdderCounter
        LongAdder a1 = new LongAdder();
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(()->{
                try {
                    barrier.await();
                    for (int j = 0; j < 100000; j++) {
                        a1.increment();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            list.add(t);
        }
        long start = System.currentTimeMillis();
        for (Thread thread : list) {
            thread.start();
        }
        for (Thread thread : list) {
            thread.join();
        }
        long end  = System.currentTimeMillis();
        System.out.println("end - start = " +( end - start) + " " + a1.longValue());
    }
}
